<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.dbshop.net/
 * @copyright Copyright (c) 2012-2017 DBShop.net Inc. (http://www.dbshop.net)
 * @license   http://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风
 *
 */

namespace Dbapi\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use \Zend\Db\Adapter\AdapterAwareInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Expression;
use Dbapi\Model\ApiGoodsIndex as dbshopCheckInData;


class ApiGoodsIndexTable extends AbstractTableGateway implements AdapterAwareInterface
{
    protected $table = 'dbshop_goods_index';

    public function setDbAdapter(Adapter $adapter)
    {
        $this->adapter     = $adapter;
        $this->initialize();
    }
    /**
     * 商品搜索(全文检索)
     * @param array $array
     * @return mixed
     */
    public function searchGoods (array $array)
    {
        $select		 = new Select(array('dbshop_goods'=>$this->table));
        $where      = dbshopCheckInData::whereGoodsData($array['where']);
        $goodsSort  = $array['order'];
        $limit      = $array['limit'];
        $offset     = $array['offset'];

        $goodsSort = !empty($goodsSort) ? (strpos($goodsSort, 'dbshop_goods.goods_shop_price')===false ? $goodsSort : new Expression($goodsSort)) : 'dbshop_goods.goods_id DESC';

        $subSql = '';
        if(isset($array['group_id']) and $array['group_id'] > 0) {
            $subSql = ',(SELECT gp.goods_user_group_price FROM dbshop_goods_usergroup_price as gp WHERE gp.goods_id=dbshop_goods.goods_id and gp.user_group_id='.$array['group_id'].' and gp.goods_color=\'\' and gp.goods_size=\'\' and gp.adv_spec_tag_id=\'\') as group_price';
        }
        $select->columns(array('*', new Expression('
        (SELECT SUM(buy_num) FROM dbshop_order_goods AS og INNER JOIN dbshop_order as do ON do.order_id=og.order_id WHERE og.goods_id=dbshop_goods.goods_id and do.order_state!=0) AS buy_num,
    	(SELECT count(favorites_id) FROM dbshop_user_favorites AS uf WHERE uf.goods_id=dbshop_goods.goods_id) AS favorites_num'
        .$subSql)));
        $select->where($where);
        $select->order($goodsSort);

        $select->limit($limit);
        $select->offset($offset);

        $resultSet = $this->selectWith($select);
        return $resultSet->toArray();
    }
}